﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
//using Consul;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Common.Encrypt;

namespace Sample.Models
{
    /// <summary>
    /// 扩展方法
    /// </summary>
    public static class ExtensionFunctions
    {
        /// <summary>
        /// 启用服务注册
        /// </summary>
        /// <param name="app"></param>
        /// <param name="configuration"></param>
        /// <param name="lifetime"></param>
        public static void UseServiceRegistration(this IApplicationBuilder app, IConfiguration configuration, IHostApplicationLifetime lifetime)
        {
            //string[] consulClient = configuration["ConsulClient"]?.Split(','); //{ "http://192.168.0.111:8500", "http://192.168.0.111:8504" };
            //if (consulClient == null || !consulClient.Any())
            //{
            //    Console.WriteLine("==================no consul address configuration==================");
            //    return;
            //}
            //string serviceName = configuration["AppName"];
            //string hostCfg = configuration["host"];
            //string serviceId = string.IsNullOrEmpty(hostCfg) ? Guid.NewGuid().ToString("N") : MD5Provider.Encode(hostCfg);

            //string[] host = hostCfg?.Split(':');
            //string ip = host[0];
            //string port = host.Length != 2 ? "80" : host[1];
            //foreach (var clientAddr in consulClient)
            //{
            //    var ccc = new ConsulClientConfiguration
            //    {
            //        Address = new Uri(clientAddr)
            //    };
            //    using (ConsulClient client = new ConsulClient(ccc))
            //    {
            //        AgentServiceRegistration asr = new AgentServiceRegistration
            //        {
            //            Address = ip,
            //            Port = Convert.ToInt32(port),
            //            ID = serviceId,
            //            Name = serviceName,
            //            Check = new AgentServiceCheck
            //            {
            //                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),
            //                HTTP = $"http://{ip}:{port}/api/Health",
            //                Interval = TimeSpan.FromSeconds(10),
            //                Timeout = TimeSpan.FromSeconds(5),
            //            },
            //        };
            //        client.Agent.ServiceRegister(asr).Wait();
            //    }
            //    lifetime.ApplicationStopping.Register(() =>
            //    {
            //        using (var consul = new ConsulClient(ccc))
            //        {
            //            Console.WriteLine("consul取消节点注册");
            //            consul.Agent.ServiceDeregister(serviceId).Wait();
            //        }
            //    });
            //}
            ////TODO: 当consul节点下线之后，如何进行重连
            //app.UseEndpoints(endpoint => endpoint.Map("/api/health", ctx => ctx.Response.WriteAsync("ok")));
        }

    }
}
